#### Script to do multiple treeMI imputations for the 2002 and 2007 ice industry
### and export the imputed dataset

#### input files:
####	ice_gooddata.csv
####
#### output files:
####	ice_imputes.csv
####    ice_predicted.csv

require(tree)

#### read in the "good" dataset, in which we have replaced the Census Bureau imputes/edits with missing values
ice_gooddata<-read.csv("ice_gooddata.csv",header=TRUE)

### Create completed datasets using treeMI:


ice_imputes<-treeMI(ice_gooddata,ITER=5,c(1,0,0,0,0,0,0,0,0,0,0,0,1,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.000001, startCut = 10, startDev = 0.00001) 

ice_imputes$impSet$impsetnum <- 1
ice_imputes$PPDsample$impsetnum <- 1

### For the first imputed dataset, create a new file
write.table(ice_imputes$impSet,file="ice_imputes.csv",append=FALSE,sep=",") 
write.table(ice_imputes$PPDsample,file="ice_predicted.csv",append=FALSE,sep=",") 

for (j in 2:500) {

  ice_imputes<-treeMI(ice_gooddata,ITER=5,c(1,0,0,0,0,0,0,0,0,0,0,0,1,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.000001, startCut = 10, startDev = 0.00001) 

  ice_imputes$impSet$impsetnum <- j
  ice_imputes$PPDsample$impsetnum <- j

  ### Append the subsequent imputed datasets to the file created for the first dataset

  write.table(ice_imputes$impSet,file="ice_imputes.csv",append=TRUE,sep=",",col.names=FALSE) 
  write.table(ice_imputes$PPDsample,file="ice_predicted.csv",append=TRUE,sep=",",col.names=FALSE) 

}


